package com.lambkit.module.cms.web.controller;

import com.lambkit.module.cms.core.template.TemplateManager;
import com.lambkit.module.cms.rpc.model.*;
import com.lambkit.module.upms.UpmsManager;
import com.lambkit.module.upms.client.ShiroClientInterceptor;
import com.lambkit.module.upms.common.LoginService;
import com.lambkit.module.upms.common.UpmsResult;
import com.lambkit.module.upms.common.UpmsResultConstant;
import com.lambkit.module.upms.rpc.api.UpmsApiService;
import com.lambkit.module.upms.rpc.model.UpmsUser;
import com.lambkit.module.upms.rpc.service.impl.UpmsApiServiceImpl;
import com.lambkit.module.upms.server.UpmsEmbeddedLoginService;
import com.lambkit.module.upms.server.interceptor.UpmsInterceptor;
import com.lambkit.module.upms.shiro.ShiroSsoInterceptor;
import com.lambkit.plugin.mail.MailKit;
import com.lambkit.plugin.mail.exception.MailSendException;
import com.lambkit.web.controller.LambkitController;
import com.lambkit.Lambkit;
import com.lambkit.common.util.EncryptUtils;
import com.lambkit.common.util.StringUtils;
import com.lambkit.component.shiro.ShiroConfig;
import com.lambkit.core.aop.AopKit;
import com.lambkit.db.sql.SqlJoinMode;
import com.lambkit.db.sql.column.Example;
import com.google.common.collect.Maps;
import com.jfinal.aop.Clear;
import com.jfinal.kit.StrKit;

import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

/**
 * 首页控制器
 * Created by shuzheng on 2017/3/19.
 */
public class IndexController extends LambkitController {

    //private static final Log LOG = Log.getLog(IndexController.class);

    LoginService loginService = new UpmsEmbeddedLoginService();
    
	@Clear({ShiroClientInterceptor.class, ShiroSsoInterceptor.class})
	public void index() {
		String style = getPara(0);
		// 所有系统
        Example cmsSystemExample = CmsSystem.sql().example().setOrderBy("orders asc");
        List<CmsSystem> systems = CmsSystem.service().find(cmsSystemExample);
        setAttr("systems", systems);
        // 所有类目
        Example cmsCategoryExample = CmsCategory.sql().example().setOrderBy("orders asc");
        cmsCategoryExample.join("system_id", "cms_system", "system_id", SqlJoinMode.LEFT_JOIN);
        cmsCategoryExample.setSelectSql("cms_category.*, cms_system.code, cms_system.name as sysname");
        List<CmsCategory> categories = CmsCategory.service().find(cmsCategoryExample);
        setAttr("categories", categories);
        // 所有标签
        Example cmsTagExample = CmsTag.sql().example().setOrderBy("orders asc");
        cmsTagExample.join("system_id", "cms_system", "system_id", SqlJoinMode.LEFT_JOIN);
        cmsTagExample.setSelectSql("cms_tag.*, cms_system.code, cms_system.name as sysname");
        List<CmsTag> tags = CmsTag.service().find(cmsTagExample);
        setAttr("tags", tags);
		// 登录信息
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        if(StrKit.notBlank(username)) {
        	UpmsUser upmsUser = UpmsManager.me().getUpmsApiService().selectUpmsUserByUsername(username);
        	//UpmsUser upmsUser = getAttr("upmsUser");
    		if("3038D9CB63B3152A79B8153FB06C02F7".equals(upmsUser.getPassword())) {
    			setAttr("name", upmsUser.getUsername());
    			String token = StringUtils.uuid();
    			UpmsManager.me().getCache().set(upmsUser.getUsername() + "-emailpswd-token", token, 180);
    	    	setAttr("token", token);
    			setAttr("upmsUser", upmsUser);
    			setAttr("msg", "初始密码需要重置才能访问！");
    			render(TemplateManager.me().getCurrentWebPath() + "/user_reset.html");
    			return;
    		}
        }
        if(StrKit.notBlank(style)) {
        	 render(TemplateManager.me().getCurrentWebPath() + "/index_" + style + ".html");        	
        } else {
        	 render(TemplateManager.me().getCurrentWebPath() + "/index.html");
        }
	}
	
	public void overview() {
    	render(TemplateManager.me().getCurrentWebPath() + "/overview.html");
    }
	
	@Clear({ShiroClientInterceptor.class, ShiroSsoInterceptor.class, UpmsInterceptor.class})
	public void login() {
		if (getRequest().getMethod().equals("GET")) {
			render(TemplateManager.me().getCurrentWebPath() + "/user_login.html");
		} else {
			loginService.login(this);
		}
	}
	
	@Clear
	public void captcha() {
		loginService.captcha(this);
	}
	
	public void regist() {
		setAttr("title", "注册");
		createToken("registToken");
		render(TemplateManager.me().getCurrentWebPath() + "/user_regist.html");
	}
	
	@Clear//@Before(UCodeInterceptor.class)
	public void logout() {
		loginService.logout(this);
	}
	
	@Clear({ShiroClientInterceptor.class, ShiroSsoInterceptor.class})
    public void forgot() {
		if (getRequest().getMethod().equals("GET")) {
			render(TemplateManager.me().getCurrentWebPath() + "/user_forgot.html");
		} else {
			String LoginName = getPara(0, getPara("name"));
			String email = getPara(1, getPara("email"));
	    	if(StringUtils.isBlank(LoginName)) {
	    		renderJson(new UpmsResult(UpmsResultConstant.EMPTY_USERNAME, "帐号不能为空！"));
				return;
	    	}
	    	if(StringUtils.isBlank(email)) {
	    		renderJson(new UpmsResult(UpmsResultConstant.EMPTY_CAPTCHA, "邮箱不能为空！"));
				return;
	    	}
	    	UpmsApiService upmsApiService = AopKit.get(UpmsApiServiceImpl.class);
			UpmsUser user = upmsApiService.selectUpmsUserByLoginName(LoginName);
			if(user==null) {
				renderJson(new UpmsResult(UpmsResultConstant.INVALID_USERNAME, "帐号不存在！"));
				return;
			}
			if(StringUtils.isBlank(user.getEmail())) {
				renderJson(new UpmsResult(UpmsResultConstant.FAILED, "未绑定邮箱！"));
				return;
			} else if(!email.equals(user.getEmail())) {
				renderJson(new UpmsResult(UpmsResultConstant.INVALID_CAPTCHA, "邮箱不正确！"));
				return;
			}
			String token = StringUtils.uuid();
			UpmsManager.me().getCache().set(user.getUsername() + "-emailpswd-token", token, 180);
			Map<String, Object> dataMap = Maps.newHashMap();
			dataMap.put("token", token);
			dataMap.put("username", user.getUsername());
			dataMap.put("email", user.getEmail());
			dataMap.put("user", user);
			try {
				MailKit.send(user.getEmail(), null, "注册账号密码重置邮件", TemplateManager.me().getCurrentWebPath() + "/email/pswd.html", dataMap);
			} catch (MailSendException e) {
				e.printStackTrace();
				renderJson(new UpmsResult(UpmsResultConstant.FAILED, "邮件发送失败！"));
				return;
			}
			renderJson(new UpmsResult(UpmsResultConstant.SUCCESS, "邮件已发送！"));
		}
    }
	
	@Clear({ShiroClientInterceptor.class, ShiroSsoInterceptor.class})
	public void reset() {
		if (getRequest().getMethod().equals("GET")) {
			keepPara();
			String name = getPara(0, getPara("name"));
	    	String token = getPara(1, getPara("token"));
	    	setAttr("name", name);
	    	setAttr("token", token);
	    	UpmsApiService upmsApiService = AopKit.get(UpmsApiServiceImpl.class);
			UpmsUser upmsUser = upmsApiService.selectUpmsUserByUsername(name);
			if(upmsUser==null) {
				setAttr("code", 0);
			} else {
				setAttr("code", 1);
			}
			setAttr("upmsUser", upmsUser);
			render(TemplateManager.me().getCurrentWebPath() + "/user_reset.html");
    	} else {
    		String name = getPara("name");
	    	String token = getPara("token");
	    	String pswd = getPara("pswd");
	    	String repswd = getPara("repswd");
	    	if(pswd.equals("")||repswd.equals("")){
				renderJson(new UpmsResult(UpmsResultConstant.FAILED, "请填写完整信息"));
				return;
			}else if(!pswd.equals(repswd)){
				renderJson(new UpmsResult(UpmsResultConstant.FAILED, "新密码必须和确认新密码一样"));
				return;
			}else if(pswd.length()<6||pswd.length()>12){
				renderJson(new UpmsResult(UpmsResultConstant.FAILED, "新密码的长度为6-12位"));
				return;
			}
	    	if (StringUtils.isBlank(name)) {
	    		renderJson(new UpmsResult(UpmsResultConstant.EMPTY_USERNAME, "帐号不能为空！"));
	    		return;
	        }
	        if (StringUtils.isBlank(token)) {
	        	renderJson(new UpmsResult(UpmsResultConstant.EMPTY_CAPTCHA, "链接已过期！"));
	        	return;
	        }
	    	UpmsApiService upmsApiService = AopKit.get(UpmsApiServiceImpl.class);
			UpmsUser upmsUser = upmsApiService.selectUpmsUserByUsername(name);
			if(upmsUser==null) {
				renderJson(new UpmsResult(UpmsResultConstant.INVALID_USERNAME, "帐号不存在！"));
			} else {
				String localToken = UpmsManager.me().getCache().get(upmsUser.getUsername() + "-emailpswd-token");
				System.out.println(localToken);
				if(!token.equals(localToken)) {
					renderJson(new UpmsResult(UpmsResultConstant.INVALID_CAPTCHA, "链接已过期！"));
		        	return;
				}
				String md5pswd = EncryptUtils.MD5(pswd+upmsUser.getSalt());
				upmsUser.setPassword(md5pswd);
				Boolean flag = upmsUser.update();
				if(flag) renderJson(new UpmsResult(UpmsResultConstant.SUCCESS, "更新成功"));
				else renderJson(new UpmsResult(UpmsResultConstant.FAILED, "更新失败"));
			}
		}
	}
	
	@Clear
	public void needPermission() {
		ShiroConfig config = Lambkit.config(ShiroConfig.class);
		render(TemplateManager.me().getCurrentWebPath() + "/" + config.getUnauthorizedUrl());
	}
	
	@Clear
	public void ViewerJS() {
		render("/ViewerJS/index.html");
	}
}